const router = require('koa-router')()
const { query } = require("../db")
const { URL } = require("url");
const path = require("path");
const fs = require("fs");
router.prefix('/history');

//朝代页
router.get('/', async (ctx, next) => {
  let urlObj = new URL(ctx.req.url, "http://localhost:3000/")
  let name = urlObj.pathname.split("/");
  let dynasty = urlObj.searchParams.get("dynasty")
  let sql = "select * from dynasty where dynasty='" + dynasty + "'" //sql语句
  const data = await query(sql)
  ctx.body = data

})
//朝代详情详情图片
router.get('/images', async (ctx, next) => {
  let urlObj = new URL(ctx.req.url, "http://localhost:3000/")
  let img_name = urlObj.searchParams.get("img")
  let filePath = path.join("./public/images/detail_images", img_name);
  let fileContent = fs.readFileSync(filePath);
  console.log(fileContent)
  ctx.res.writeHead(200, { "Content-Type": "image" });
  ctx.res.end(fileContent);

})

//朝代页搜索
router.get("/search", async (ctx, next) => {
  console.log(ctx.request.query.info)
  console.log(ctx.request.query.dynasty)
  let sql = `select * from dynasty where title like '%${ctx.request.query.info}%' and dynasty = '${ctx.request.query.dynasty}'`;
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//文物页
router.get("/relic", async (ctx, next) => {
  let sql = "select * from relic";
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//历史大事件页
router.get("/accident", async (ctx, next) => {
  let sql = "select * from accident";
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//历史作品页
router.get("/work", async (ctx, next) => {
  let sql = "select * from work";
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//历史作品详情页
router.get("/work/detail", async (ctx, next) => {
  let sql = "select * from work where book_id='" + ctx.request.query.id + "'";
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//历史人物页
router.get("/people", async (ctx, next) => {
  let sql = "select * from people";
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//历史人物详情页
router.get("/people/detail", async (ctx, next) => {
  let sql = "select * from people where people_id='" + ctx.request.query.id + "'";
  let results = await query(sql, []);
  ctx.res.end(JSON.stringify(results));
})

//从服务端获取图片响应到页面
router.get("/:id", async (ctx, next) => {
  let urlObj = new URL(ctx.req.url, "http://localhost:3000/")
  let name = urlObj.pathname.split("/");
  let filePath = path.join("./public/images/images/" + name[2]);
  let fileContent = fs.readFileSync(filePath);
  ctx.res.writeHead(200, { "Content-Type": "image/png" });
  ctx.res.end(fileContent);
})

module.exports = router